package com.yuyu.task;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.yuyu.entity.User;
import com.yuyu.service.UserService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/19  8:49
 * 描述:
 */

@Component
public class MyTask1 implements SimpleJob {


    @Autowired
    private UserService userService;


    @Override
    public void execute(ShardingContext shardingContext) {
        //当前的分片编号
        int shardingItem = shardingContext.getShardingItem();
        List<User> users = new ArrayList<>();


        if(shardingItem==0){

            RestHighLevelClient client = new RestHighLevelClient(
                    RestClient.builder(
                            new HttpHost("localhost", 9200, "http")));

            SearchRequest searchRequest = new SearchRequest("2021-03-25_1_1");

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            searchSourceBuilder.from(0);
            searchSourceBuilder.size(2);

            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = null;
            try {
                searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            SearchHit[] hits = searchResponse.getHits().getHits();
            for (SearchHit hit : hits) {
                hit.getSourceAsString();
                String sourceAsString = hit.getSourceAsString();
                User user = JSON.parseObject(sourceAsString, User.class);
                users.add(user);
                System.out.println(hit.getSourceAsString());
            }
            //用规则判断

            userService.panduan(users);

            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else if(shardingItem==1){

            System.out.println("----------分片二");


        }

    }
}
